package com.lql.algorithm.kmp;

/**
 * 暴力匹配，查找字符
 */
public class ViolentMatching {
    public static void main(String[] args) {
        String str1 = "硅硅谷 尚硅谷你尚硅 尚硅谷你尚硅谷你尚硅你好";
        String str2 = "尚硅谷你尚硅你";
        System.out.println(violentMatching(str1, str2));

    }

    /**
     * 暴力匹配
     *
     * @param str1 被匹配的字符串
     * @param str2 待匹配的字符串
     * @return 查找到的字符下标索引，否则返回-1
     */
    public static int violentMatching(String str1, String str2) {
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();

        int i = 0;//索引一
        int j = 0;//索引二

        while (i < chars1.length && j < chars2.length) {
            if (chars1[i] == chars2[j]) {
                //匹配成功
                i++;
                j++;
            } else {
                //匹配失败，j回溯到0，i回溯到i-(j-1)
                i = i - (j - 1);
                j = 0;
            }
        }
        if (j == chars2.length) {
            //查找到
            return i - j;
        } else {
            //未查到
            return -1;
        }
    }
}
